package com.xiaolei.openokjoke.RecyclerView

import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.support.annotation.ColorInt
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View

/**
 * Created by xiaolei on 2017/12/22.
 */
class ColorDecoration(val strokeWidth: Int // 宽度
                      , @ColorInt val color: Int //什么颜色
) : RecyclerView.ItemDecoration()
{
    private val mDivider by lazy {
        ColorDrawable(color)
    }

    override fun onDraw(c: Canvas?, parent: RecyclerView?, state: RecyclerView.State?)
    {
        drawHDeraction(c!!, parent!!)
        drawVDeraction(c, parent)
    }

    /**
     * 绘制水平方向的分割线
     * @param c
     * @param parent
     */
    private fun drawHDeraction(c: Canvas, parent: RecyclerView)
    {
        val left = parent.paddingLeft
        val right = parent.width - parent.paddingRight
        val childCount = parent.childCount
        for (i in 0 until childCount)
        {
            val child = parent.getChildAt(i)
            val layoutParams = child.layoutParams as RecyclerView.LayoutParams
            val top = child.bottom + layoutParams.bottomMargin
            val bottom = top + strokeWidth
            mDivider.setBounds(left, top, right, bottom)
            mDivider.draw(c)
        }
    }

    /**
     * 绘制垂直方向的分割线
     * @param c
     * @param parent
     */
    private fun drawVDeraction(c: Canvas, parent: RecyclerView)
    {
        val top = parent.paddingTop
        val bottom = parent.height - parent.paddingBottom
        val childCount = parent.childCount
        for (i in 0 until childCount)
        {
            val child = parent.getChildAt(i)
            val layoutParams = child.layoutParams as RecyclerView.LayoutParams
            val left = child.right + layoutParams.rightMargin
            val right = left + strokeWidth
            mDivider.setBounds(left, top, right, bottom)
            mDivider.draw(c)
        }
    }

    override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?)
    {
        val layoutManager = parent?.layoutManager
        if (layoutManager is LinearLayoutManager)
        {
            if (LinearLayoutManager.HORIZONTAL == layoutManager.orientation)
            {
                outRect?.set(0, 0, strokeWidth, 0)
            } else
            {
                outRect?.set(0, 0, 0, strokeWidth)
            }
        }
    }
}